package user

import (
	"context"
	"strconv"

	"mall/common/modelx"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetUserByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetUserByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetUserByIdLogic {
	return &BackendGetUserByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendGetUserByIdLogic) BackendGetUserById(in *user.IDReq) (*user.TmpUserInfo, error) {
	if in.Id == 0 {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	res, err := l.svcCtx.User.FindOne(l.ctx, int64(in.Id), nil)
	if err != nil {
		return nil, err
	}
	var userEmailVerified uint32
	var mobileVerified uint32
	var isSystem uint32
	if res.UserEmailVerified > 0 {
		userEmailVerified = 1
	}
	if res.UserMobileVerified > 0 {
		mobileVerified = 1
	}
	if res.IsSystem > 0 {
		isSystem = 1
	}

	return &user.TmpUserInfo{
		Id:       pointy.GetPointer(strconv.Itoa(int(res.ID))),
		Username: pointy.GetPointer(res.UserLogin),
		Email:    pointy.GetPointer(res.UserEmail),
		Mobile:   pointy.GetPointer(res.UserMobile),
		Status:   pointy.GetPointer(uint32(res.UserStatus)),
		// LastLoginTime:    pointy.GetPointer(modelx.FormatNullDotTime(res.LastLoginTime, "")),
		CreatedAt:        pointy.GetPointer(modelx.FormatTime(res.CreatedAt, "")),
		UpdatedAt:        pointy.GetPointer(modelx.FormatTime(res.UpdatedAt, "")),
		DeletedAt:        pointy.GetPointer(modelx.FormatNullDotTime(res.DeletedAt, "")),
		EmailVerified:    pointy.GetPointer(userEmailVerified),
		EmailVerifiedAt:  pointy.GetPointer(modelx.FormatNullDotTime(res.UserEmailVerifiedAt, "")),
		MobileVerified:   pointy.GetPointer(mobileVerified),
		MobileVerifiedAt: pointy.GetPointer(modelx.FormatNullDotTime(res.UserMobileVerifiedAt, "")),
		CreatedIP:        pointy.GetPointer(res.CreateIP),
		IsSystem:         pointy.GetPointer(isSystem),
	}, nil
}
